/* 
 * @name administration.js
 * @author : Amissah Gideon<kuulmek@yahoo.com>
 */
var ManageProforma = {
    /* Server script url   */
    ssUrl:'Items/add',
    selected_row_id:null,

    /* dataTable Object */
    objGrid:null,

    /* Function init
     * @param void
     * @return void
     * @access public
     * */
    init:function () {
        var self = this;
        /*Sortable Table */
        var oTable = null;
        var dataUrl = $('#table-url').val();

        self.objGrid = $('#flex').flexigrid({
            url:dataUrl,
            dataType:'json',
            colModel:[
                {display:'ID', name:'id', width:20, sortable:false, align:'left', hide:true},
                {display:'Date Create', name:'created', width:80, sortable:true, align:'center', hide:false},
                {display:'Proforma Number', name:'invoice_number', width:130, sortable:true, align:'center', hide:false},
                {display:'Sales Type', name:'sales_type', width:135, sortable:true, align:'center', hide:false},
                {display:'Customer', name:'customer_id', width:225, sortable:false, align:'center', hide:false},
                {display:'Sales', name:'made_sales', width:70, sortable:false, align:'center', hide:false},
                {display:'Created By', name:'created_by', width:160, sortable:false, align:'center', hide:false}
            ],
            formFields:[
                /*{type:'buttom', name:'View More Info', bclass:'view', onpress:self.handleGridEvent},
                {separator:true},*/
                {type:'buttom', name:'Reprint', bclass:'print', onpress:self.handleGridEvent},
                {separator:true},
                {type:'buttom', name:'Delete', bclass:'delete', onpress:self.handleGridEvent}
                /*{separator:true},
                {type:'select', name:'Filter On Sales', id:'filter_sales' ,bclass:'person', options:gbl_sale_filter , onchange:self.handleGridEvent}*/
            ],
            searchitems:[
                {display:'Proforma Number', name:'invoice_number', isdefault:true}
            ],
            checkboxSelection:true,
            columnControl:true,
            sortname:"id",
            sortorder:"desc",
            usepager:true,
            useRp:true,
            rp:15,
            showTableToggleBtn:false,
            height:300
        });

        $('#cancel-btn').click(function () {
            document.getElementById('form').reset();
            $.validationEngine.closePrompt('.formError', true);
            $.colorbox.close();
            self.selected_row_id = null;
        });
    },

    handleGridEvent:function (com, grid,json) {
        if (com == 'View More Info') {
            if (jLib.rowSelectedCheck(grid, 1)) {
                ManageProforma.view(jLib.getSelectedRowIds(grid));
            }
        }
        else if (com == 'Reprint') {
            if (jLib.rowSelectedCheck(grid, 1)) {
                var arr = jLib.getSelectedRowIds(grid);
                var proforma_id = arr[0];
                var action = $('#print-invoice-url').val();
                var url = action+'/'+proforma_id;
                window.open(url,action,"menubar=yes, width=600, height=500,location=no,status=no,scrollbars=yes,resizable=yes");
            }
        }
        else if (com == 'Delete') {
            if (jLib.rowSelectedCheck(grid)) {
                ManageProforma.delete_(grid);
            }
        }
        else if (com == 'Filter On Sales') {
            ManageProforma.filterOnSales(json);
        }
    },

    filterOnSales:function(value){
        var self = this;
        self.objGrid.flexOptions({params: [{name:'made_sale_pr',value:value}]}).flexReload();
        return false;
    },

    view:function (row_ids) {

        var self = this;
        var dataID = row_ids[0];
        var url = $('#load-user-url').val();
        var query = 'type=load&data-id=' + dataID;

        $.ajax({
            url:url,
            data:query,
            dataType:'json',
            type:'POST',
            success:function (response) {
                var txt = '';
                if (typeof response.mesg == 'object') {
                    for (megTxt in response.mesg) {
                        txt += response.mesg[megTxt] + '<br />';
                    }
                }
                else {
                    txt = response.mesg
                }
                //* When everything went on smoothly on the server redirect the user to the appropriate page.*//*
                if (response.code === 0) {
                    console.log(response.data);
                    var Customer = response.data.Customer;
                    var Proforma = response.data.Proforma;
                    var ProformaItem = response.data.ProformaItem;
                    var User = response.data.User;

                    $('#form-window p span.proforma_date').html(Proforma['created']);
                    $('#form-window p span.proforma_number').html(Proforma['proforma_number']);
                    $('#form-window p span.customer').html(Customer['name']);
                    $('#form-window p span.created_by').html(User['first_name']+' '+User['middle_name']+' '+User['last_name']);

                    self.selected_row_id = dataID;

                    $.colorbox({
                        inline:true,
                        scrolling:false,
                        overlayClose:false,
                        escKey:false,
                        title:'Proforma Information',
                        href:"#form-window"
                    });
                }
                //* When there are Errors *//*
                else if (response.code === 1) {
                    jLib.serverError(txt);
                }
            },
            error:function (xhr) {
                console.log(xhr.responseText);
                jLib.serverError();
            }
        });
    },

    save:function () {
        var self = this;
        /* Validate the form*/
        var validationStatus = $('#form').validationEngine({returnIsValid:true});
        /* When the Validation Status is true meaning that the data input are correct then the data can be processed. */
        if (validationStatus) {

            jLib.showFormLoading();

            var query = 'model=Item&row_id=' + self.selected_row_id + '&' + $('#form').serialize();
            var url = $("#add-edit-url").val();
            /* Send the data to the server and handle the server response */

            $.ajax({
                url:url,
                data:query,
                dataType:'json',
                type:'POST',
                success:function (response) {
                    var txt = '';
                    if (typeof response.mesg == 'object') {
                        for (megTxt in response.mesg) {
                            txt += response.mesg[megTxt] + '<br />';
                        }
                    }
                    else {
                        txt = response.mesg
                    }
                    //* When everything went on smoothly on the server redirect the user to the appropriate page.*//*
                    if (response.code === 0) {

                        jLib.message(txt, 'success');

                        if(self.selected_row_id){

                            var cedi_amount = 0.00;
                            if ($('#form-window #form #currency').val() == '$') {
                                cedi_amount = parseFloat($('#form-window #form #amount').val()) * parseFloat($('#form-window #form #usd_rate').val());
                            }
                            else {
                                cedi_amount = $('#form-window #form #amount').val();
                            }
                            // Chnge the cell data
                            var update_data = {
                                'name':$('#form-window #form #name').val(),
                                'specs':$('#form-window #form #specs').val(),
                                'currency':$('#form-window #form #currency').val(),
                                'amount':$('#form-window #form #amount').val(),
                                'usd_rate':$('#form-window #form #usd_rate').val(),
                                'cedi_amount':cedi_amount,
                                'comments':$('#form-window #form #comments').val()
                                //'status': $('#form-window #form #routine_status option:selected').text(),
                            };

                            jLib.updateGridData(self.objGrid, update_data);
                            //
                            jLib.highlightRow(self.objGrid);
                        }
                        else{
                            $(self.objGrid).flexReload();
                        }
                        document.getElementById('form').reset();
                        $.validationEngine.closePrompt('.formError',true);
                        $.colorbox.close();
                        self.selected_row_id = null;
                    }
                    //* When there are Errors *//*
                    else if (response.code === 1) {
                        jLib.serverError(txt);
                    }

                    jLib.hideFormLoading();
                },
                error:function (xhr) {
                    console.log(xhr.responseText);
                    jLib.serverError();
                }
            });
        }
    },


    delete_:function (grid) {
        var self = this;
        var url = $('#delete-url').val();
        jLib.do_delete(url, grid);
    }

};

/* when the page is loaded */
$(document).ready(function () {
    ManageProforma.init();
});